/**
 * 上下文感知的Prompt增强器
 * 
 * 功能：将已收集的类上下文和函数调用关系明确展示给LLM
 * - 类的构造函数和成员变量
 * - 当前函数调用的其他函数（静态/成员/普通函数）
 * - 函数签名和调用关系
 */

import { FuncCalledInfo } from './entities/types';

export class ContextAwarePromptEnhancer {
    
    /**
     * 增强Prompt，添加完整的上下文信息
     */
    public static enhanceWithFullContext(
        basePrompt: string,
        classContext: {
            sourceClass?: string;
            sourceClassConstructors?: { [key: string]: string[] };
            sourceClassMembers?: string[];
            source_class_fields?: string;
            signature?: string;
            is_static_method?: boolean;
            funcCalledList?: FuncCalledInfo[];
            returnType?: string;
            paramDefinitions?: string[];
        }
    ): string {
        let enhanced = basePrompt;
        
        if (!classContext || !classContext.sourceClass) {
            return enhanced;
        }
        
        enhanced += '\n\n' + '━'.repeat(80) + '\n';
        enhanced += '## 🎯 被测函数的完整上下文（充分利用这些信息编写准确的测试）\n';
        enhanced += '━'.repeat(80) + '\n\n';
        
        // 1. 类名和基本信息
        enhanced += `### 📦 类名：\`${classContext.sourceClass}\`\n\n`;
        
        // 2. 静态方法特殊提示（放在最前面，最重要）
        if (classContext.is_static_method) {
            enhanced += '### ⚠️ 这是静态方法（重要！）\n\n';
            enhanced += '```cpp\n';
            enhanced += `// ✅ 静态方法无需创建类实例，直接通过类名调用\n`;
            enhanced += `TEST_F(${classContext.sourceClass}Test, TestMethod001) {\n`;
            enhanced += `    // 直接调用，不需要 instance_->\n`;
            enhanced += `    auto result = ${classContext.sourceClass}::${classContext.signature?.split('(')[0] || 'MethodName'}(...);\n`;
            enhanced += `    EXPECT_EQ(result, expectedValue);\n`;
            enhanced += `}\n`;
            enhanced += '```\n\n';
            enhanced += '**💡 关键点**：\n';
            enhanced += '- ✅ 不需要在SetUp()中创建对象\n';
            enhanced += '- ✅ 直接使用 `ClassName::MethodName()` 调用\n';
            enhanced += '- ✅ 测试类可以简化，不需要 instance_ 成员变量\n\n';
        }
        
        // 3. 构造函数信息（非静态方法需要）
        if (!classContext.is_static_method && classContext.sourceClassConstructors) {
            const publicCtors = classContext.sourceClassConstructors.public || [];
            const protectedCtors = classContext.sourceClassConstructors.protected || [];
            
            if (publicCtors.length > 0 || protectedCtors.length > 0) {
                enhanced += '### 🏗️ 可用的构造函数：\n\n';
                
                if (publicCtors.length > 0) {
                    enhanced += '**Public构造函数**：\n';
                    enhanced += '```cpp\n';
                    publicCtors.forEach((ctor: string) => {
                        enhanced += `${ctor}\n`;
                    });
                    enhanced += '```\n\n';
                }
                
                if (protectedCtors.length > 0) {
                    enhanced += '**Protected构造函数**：\n';
                    enhanced += '```cpp\n';
                    protectedCtors.forEach((ctor: string) => {
                        enhanced += `${ctor}\n`;
                    });
                    enhanced += '```\n\n';
                }
                
                enhanced += '**💡 在SetUp()中初始化测试对象**：\n';
                enhanced += '```cpp\n';
                enhanced += `void SetUp() override {\n`;
                enhanced += `    // 使用智能指针管理对象\n`;
                enhanced += `    instance_ = std::make_shared<${classContext.sourceClass}>(/* 根据构造函数传入参数 */);\n`;
                enhanced += `}\n`;
                enhanced += '```\n\n';
            }
        }
        
        // 4. 成员变量信息
        if (classContext.sourceClassMembers && classContext.sourceClassMembers.length > 0) {
            enhanced += '### 📋 类的成员变量：\n\n';
            enhanced += '```cpp\n';
            const membersToShow = classContext.sourceClassMembers.slice(0, 15);
            membersToShow.forEach((member: string) => {
                enhanced += `${member}\n`;
            });
            if (classContext.sourceClassMembers.length > 15) {
                enhanced += `// ... 还有 ${classContext.sourceClassMembers.length - 15} 个成员变量\n`;
            }
            enhanced += '```\n\n';
            enhanced += '**💡 测试时的关键点**：\n';
            enhanced += '- ✅ 这些成员变量可能影响被测函数的行为\n';
            enhanced += '- ✅ 考虑成员变量的不同状态组合（初始化/未初始化、nullptr/有效值）\n';
            enhanced += '- ✅ 如果成员是智能指针或容器，测试空和非空情况\n';
            enhanced += '- ✅ 可能需要在SetUp()中Mock某些成员变量\n\n';
        }
        
        // 5. 函数调用关系（最重要的部分！）
        if (classContext.funcCalledList && classContext.funcCalledList.length > 0) {
            enhanced += '### 🔗 当前函数调用的其他函数（必须了解！）\n\n';
            
            // 分类统计
            const staticCalls: FuncCalledInfo[] = [];
            const memberCalls: FuncCalledInfo[] = [];
            const globalCalls: FuncCalledInfo[] = [];
            const virtualCalls: FuncCalledInfo[] = [];
            
            classContext.funcCalledList.forEach(call => {
                if (call.isVirtual) {
                    virtualCalls.push(call);
                } else if (call.isStatic) {
                    staticCalls.push(call);
                } else if (call.isGlobleFun) {
                    globalCalls.push(call);
                } else if (call.sourceClassName) {
                    memberCalls.push(call);
                }
            });
            
            enhanced += `**统计**：共调用 ${classContext.funcCalledList.length} 个函数\n`;
            if (staticCalls.length > 0) enhanced += `- 静态函数：${staticCalls.length} 个\n`;
            if (memberCalls.length > 0) enhanced += `- 成员函数：${memberCalls.length} 个\n`;
            if (globalCalls.length > 0) enhanced += `- 全局函数：${globalCalls.length} 个\n`;
            if (virtualCalls.length > 0) enhanced += `- 虚函数：${virtualCalls.length} 个（**需要Mock**）\n`;
            enhanced += '\n';
            
            // 详细列出静态函数调用
            if (staticCalls.length > 0) {
                enhanced += '#### 🔹 静态函数调用：\n\n';
                enhanced += '```cpp\n';
                staticCalls.slice(0, 10).forEach(call => {
                    if (call.sourceClassName) {
                        enhanced += `${call.sourceClassName}::${call.sourceFuncName}  // 静态方法\n`;
                    } else {
                        enhanced += `${call.sourceFuncName}  // 静态方法\n`;
                    }
                    if (call.signature) {
                        enhanced += `// 签名: ${call.signature}\n`;
                    }
                });
                if (staticCalls.length > 10) {
                    enhanced += `// ... 还有 ${staticCalls.length - 10} 个静态函数调用\n`;
                }
                enhanced += '```\n\n';
                enhanced += '**💡 测试建议**：\n';
                enhanced += '- ✅ 静态函数通常是工具函数或单例方法\n';
                enhanced += '- ✅ 确保这些静态函数返回期望的值\n';
                enhanced += '- ✅ 如果是 `GetInstance()` 类型，确保单例已初始化\n\n';
            }
            
            // 详细列出成员函数调用
            if (memberCalls.length > 0) {
                enhanced += '#### 🔹 成员函数调用（同类或成员变量的方法）：\n\n';
                enhanced += '```cpp\n';
                memberCalls.slice(0, 10).forEach(call => {
                    if (call.sourceClassName && call.sourceClassName === classContext.sourceClass) {
                        enhanced += `this->${call.sourceFuncName}  // 同类的成员函数\n`;
                    } else if (call.sourceClassName) {
                        enhanced += `${call.sourceClassName}::${call.sourceFuncName}  // 成员变量的方法\n`;
                    } else {
                        enhanced += `${call.sourceFuncName}  // 成员函数\n`;
                    }
                    if (call.signature) {
                        enhanced += `// 签名: ${call.signature}\n`;
                    }
                });
                if (memberCalls.length > 10) {
                    enhanced += `// ... 还有 ${memberCalls.length - 10} 个成员函数调用\n`;
                }
                enhanced += '```\n\n';
                enhanced += '**💡 测试建议**：\n';
                enhanced += '- ✅ 如果调用同类的其他成员函数，需要确保对象状态正确\n';
                enhanced += '- ✅ 如果调用成员变量的方法（如 `member_->DoSomething()`），需要在SetUp中初始化该成员\n';
                enhanced += '- ✅ 可能需要Mock成员变量，控制其返回值\n\n';
            }
            
            // 详细列出虚函数调用（需要Mock）
            if (virtualCalls.length > 0) {
                enhanced += '#### 🎭 虚函数调用（**强烈建议Mock**）：\n\n';
                enhanced += '```cpp\n';
                virtualCalls.slice(0, 10).forEach(call => {
                    enhanced += `${call.sourceFuncName}  // 虚函数 - 需要Mock\n`;
                    if (call.signature) {
                        enhanced += `// 签名: ${call.signature}\n`;
                    }
                    if (call.virtualFunction) {
                        enhanced += `// 虚函数定义: ${call.virtualFunction}\n`;
                    }
                });
                if (virtualCalls.length > 10) {
                    enhanced += `// ... 还有 ${virtualCalls.length - 10} 个虚函数调用\n`;
                }
                enhanced += '```\n\n';
                enhanced += '**💡 Mock建议**：\n';
                enhanced += '```cpp\n';
                enhanced += `// 1. 创建Mock类\n`;
                enhanced += `class Mock${classContext.sourceClass} : public ${classContext.sourceClass} {\n`;
                enhanced += `public:\n`;
                virtualCalls.slice(0, 3).forEach(call => {
                    enhanced += `    MOCK_METHOD(/* ReturnType */, ${call.sourceFuncName}, (/* params */), (override));\n`;
                });
                enhanced += `};\n\n`;
                enhanced += `// 2. 在测试中使用\n`;
                enhanced += `TEST_F(${classContext.sourceClass}Test, TestWithMock001) {\n`;
                enhanced += `    auto mock = std::make_shared<Mock${classContext.sourceClass}>();\n`;
                enhanced += `    EXPECT_CALL(*mock, ${virtualCalls[0]?.sourceFuncName}(...))\n`;
                enhanced += `        .WillOnce(Return(expectedValue));\n`;
                enhanced += `    // 测试逻辑\n`;
                enhanced += `}\n`;
                enhanced += '```\n\n';
            }
            
            // 详细列出全局函数调用
            if (globalCalls.length > 0) {
                enhanced += '#### 🔹 全局函数/外部函数调用：\n\n';
                enhanced += '```cpp\n';
                globalCalls.slice(0, 10).forEach(call => {
                    enhanced += `${call.sourceFuncName}  // 全局函数\n`;
                    if (call.signature) {
                        enhanced += `// 签名: ${call.signature}\n`;
                    }
                });
                if (globalCalls.length > 10) {
                    enhanced += `// ... 还有 ${globalCalls.length - 10} 个全局函数调用\n`;
                }
                enhanced += '```\n\n';
                enhanced += '**💡 测试建议**：\n';
                enhanced += '- ✅ 确保全局函数的前置条件满足\n';
                enhanced += '- ✅ 如果是系统API，检查返回的错误码\n';
                enhanced += '- ✅ 可能需要环境准备（如创建临时文件、设置权限等）\n\n';
            }
        }
        
        // 6. 函数签名和参数
        if (classContext.signature) {
            enhanced += '### 📝 被测函数签名：\n\n';
            enhanced += '```cpp\n';
            enhanced += `${classContext.signature}\n`;
            enhanced += '```\n\n';
            
            if (classContext.returnType) {
                enhanced += `**返回类型**：\`${classContext.returnType}\`\n\n`;
            }
            
            if (classContext.paramDefinitions && classContext.paramDefinitions.length > 0) {
                enhanced += '**参数说明**：\n';
                classContext.paramDefinitions.slice(0, 10).forEach((param: string) => {
                    enhanced += `- \`${param}\`\n`;
                });
                enhanced += '\n';
            }
        }
        
        // 7. 测试策略总结
        enhanced += '### 🎯 综合测试策略：\n\n';
        enhanced += '1. **对象初始化**：\n';
        if (classContext.is_static_method) {
            enhanced += '   - ✅ 静态方法，无需创建对象实例\n';
        } else {
            enhanced += '   - ✅ 在SetUp()中使用 `std::make_shared` 创建测试对象\n';
            enhanced += '   - ✅ 根据构造函数参数传入合适的测试数据\n';
        }
        enhanced += '\n';
        
        enhanced += '2. **成员变量状态**：\n';
        if (classContext.sourceClassMembers && classContext.sourceClassMembers.length > 0) {
            enhanced += '   - ✅ 考虑成员变量的不同状态（nullptr、有效值、边界值）\n';
            enhanced += '   - ✅ 可能需要Mock某些成员变量\n';
        } else {
            enhanced += '   - ✅ 该函数可能不依赖成员变量\n';
        }
        enhanced += '\n';
        
        enhanced += '3. **函数调用处理**：\n';
        if (classContext.funcCalledList && classContext.funcCalledList.length > 0) {
            const hasVirtual = classContext.funcCalledList.some(c => c.isVirtual);
            const hasMember = classContext.funcCalledList.some(c => c.sourceClassName);
            
            if (hasVirtual) {
                enhanced += '   - ⭐ **必须Mock虚函数**，使用EXPECT_CALL设置期望\n';
            }
            if (hasMember) {
                enhanced += '   - ✅ 确保被调用的成员函数能正常工作或被Mock\n';
            }
            enhanced += '   - ✅ 验证函数调用的顺序和次数\n';
        }
        enhanced += '\n';
        
        enhanced += '4. **测试用例设计**：\n';
        enhanced += '   - ✅ 正常流程：典型使用场景\n';
        enhanced += '   - ✅ 边界条件：nullptr、空字符串、最大最小值\n';
        enhanced += '   - ✅ 异常处理：错误参数、系统调用失败\n';
        enhanced += '   - ✅ 状态验证：检查对象状态变化和返回值\n';
        enhanced += '\n';
        
        enhanced += '━'.repeat(80) + '\n\n';
        
        return enhanced;
    }
}

